package com.chengjue.rocketmq;

import com.chengjue.rocketmq.listener.MessageListener;
import com.chengjue.rocketmq.manager.RocketMQManager;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Kipeng Huang
 * @Date: 2018-4-12 15:37
 */
@Configuration
public class RocketMqConfig {
    @Value("${apache.rocketmq.producer.producerGroup}")
    private String producerGroup;
    @Value("${apache.rocketmq.namesrvAddr}")
    private String namesrvAddr;
    @Value("${apache.rocketmq.consumer.PushConsumer}")
    private String consumerGroup;

    @Bean(value = "mqProducer")
    public DefaultMQProducer defaultMQProducer() throws MQClientException {
        DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(namesrvAddr);
        producer.start();
        return producer;
    }

    @Bean("mqConsumer")
    public DefaultMQPushConsumer pushConsumer () throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(namesrvAddr);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        return consumer;
    }

    @Bean("rocketMQManager")
    public RocketMQManager rocketMQManager(MessageListener messageListener, DefaultMQPushConsumer mqConsumer){
        List<MessageListener> messageListeners= new ArrayList<>();
        messageListeners.add(messageListener);
        return new RocketMQManager(mqConsumer,messageListeners,"xinyu-message","test");

    }



}
